<!--
 * @description: 氢 预测结果
 * @author: cuicui
 * @Date: 2023-11-23 11:55:06
 * @LastEditTime: 2023-11-23 14:17:10
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='历史数据' custom-title>
    <template slot='header'>
      <div class='table-tab'>
        <a-tabs v-model='activeKey' type='editable-card' @edit='handleEditTab'>
          <a-tab-pane v-for='item in tabs' :key='item.id'>
            <span slot='tab'>
              <a-icon type='edit' class='edit-tab-color' @click.stop='handleEditTab(item.id, "edit")' />
              {{ item.pageName }}
            </span>
          </a-tab-pane>
        </a-tabs>
      </div>

      <div class='table-operator' style='height: 20px'>
        <a-button style='float: right' type='primary' icon='plus' @click='handleAdd'>新建</a-button>
      </div>
    </template>
    <div style='height: 100%;'>
      <history-chart-item
        v-show='reportList.length'
        :mark='item.mark'
        :moduleId='moduleId'
        v-for='item in reportList'
        :chart-type-code='item.reportTypeDicId'
        :key='item.id'
        :report-name='item.reportName'
        :char-key='item.id'
        @remove='handleRemove(item)'
        @edit='pointList => handleEdit(item, pointList)'
      />
      <a-empty style='height: 100%' v-show='!reportList.length'/>
    </div>
    <create-chart
      :moduleId='moduleId'
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @up-loading='(bol)=> confirmLoading = bol'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <create-tab
      :title='"页面"'
      ref='createTab'
      :visible='historyVisible'
      :loading='confirmLoading'
      :model='historyTimeModel'
      @cancel='handlHistoryTimeeCancel'
      @ok='handleHistoryOk' />
  </business-layout>
</template>

<script>
import { LineChart, BarChart } from '@/business-components/charts'
import CreateChart from '@/business-components/create-chart/index.vue'
import CreateTab from '@/business-components/create-tab/index.vue'
import HistoryChartItem from '@/business-components/history-chart-item/index.vue'
import {
  create,
  update,
  findAllPageByModuleId,
  remove,
  removeReport,
  findAllReportByPageId,
  createChart,
  updateChart
} from '@/api/historyTime'
import CreatePoint from '@/business-components/create-point/index.vue'

// 模块id 不同模块id不同
const moduleId = '03'
const pageType = 'forecast'
let mark = 0
export default {
  name: 'HistoryTime',
  mixins: [],
  components: {
    CreatePoint,
    CreateTab,
    LineChart,
    BarChart,
    CreateChart,
    HistoryChartItem
  },
  props: {},
  watch: {
    activeKey(val) {
      if (val) {
        this.findAllReportByPageId()
      }
    }
  },
  computed: {},
  data() {
    this.moduleId = moduleId
    this.pageType = pageType
    return {
      activeKey: '',
      menuId: "",
      myBarChart: null,
      barSpinning: true,
      visible: false,
      mdl: null,
      historyTimeModel: null,
      tabs: [],
      historyVisible: false,
      confirmLoading: false,
      reportList: []
    }
  },
  created() {
    this.menuId = this.$route.fullPath
    this.findAllPageByModuleId()
  },
  methods: {
    async findAllReportByPageId() {
      const result = await findAllReportByPageId({
        pageId: this.activeKey
      })
      mark++
      this.reportList = result.map(item => {
        return {
          ...item,
          mark
        }
      })
    },
    // 查询tabs
    async findAllPageByModuleId() {
      this.tabs = await findAllPageByModuleId({
        moduleId,
        pageType,
        menuId: this.menuId
      })
      if (this.tabs && this.tabs.length > 0 && !this.activeKey) {
        this.activeKey = this.tabs[0].id
      }
    },
    handleEditTab(tagetKey, action) {
      if (action === 'add') {
        this.historyVisible = true
      }
      if (action === 'remove') {
        this.removeTab(tagetKey)
      }
      if (action === 'edit') {
        this.historyVisible = true
        const tabItem = this.tabs.find(item => item.id === tagetKey)
        this.historyTimeModel = {
          ...tabItem,
          pageName: tabItem.pageName
        }
      }
    },
    handlHistoryTimeeCancel() {
      const form = this.$refs.createTab.form
      form.resetFields() // 清理表单数据（可不做）

      this.historyVisible = false
    },
    removeTab(id) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        async onOk() {
          const result = await remove({ id })
          if (result) {
            that.findAllPageByModuleId()
            // 删除tab为当前选中tab的话重置到第一个选项
            if (that.activeKey === id) {
              that.activeKey = ''
            }
            that.$message.success('更新成功！')
            that.handlHistoryTimeeCancel()
          }
        }
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(value, pointList = []) {
      this.mdl = {
        ...value,
        pointIdList: pointList.map(item => item.pointId),
        deviceIdList: pointList.map(item => item.deviceId),
        systemIdList: pointList.map(item => item.systemId),
        displayNameList: pointList.map(item => item.displayName),
        colorList: pointList.map(item => item.color),
        options: pointList.map((_item, index) => index)
      }
      this.visible = true
    },
    handleRemove(value) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '该操作不可逆、是否继续？',
        onOk() {
          removeReport({
            id: value.id
          }).then(res => {
            that.findAllReportByPageId()
            that.$message.success('删除成功')
          })
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleHistoryOk() {
      const that = this
      const form = this.$refs.createTab.form
      form.validateFields(async (errs, values) => {
        if (errs) {
          return
        }
        const { pageName, id } = values
        if (!id) {
          const reulst = await create({
            moduleId,
            pageName,
            pageType,
            menuId: this.menuId
          })
          if (reulst) {
            that.findAllPageByModuleId()
            that.$message.success('创建成功！')
            that.visible = false
            that.handlHistoryTimeeCancel()
          }
          return
        }
        const reulst = await update({
          moduleId,
          id,
          pageType,
          menuId: this.menuId,
          pageName: pageName
        })
        if (reulst) {
          that.findAllPageByModuleId()
          that.$message.success('更新成功！')
          that.visible = false
          that.handlHistoryTimeeCancel()
        }
      })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      const that = this
      form.validateFields(async (errors, values) => {
        if (!errors) {
          // 准备新增与编辑需要用到的数据结构
          const submitData = {
            id: values.id,
            pageId: that.activeKey,
            reportName: values.reportName,
            reportTypeDicId: values.reportTypeDicId,
            reportItems: values.systemIdList.map((item, index) => {
              return {
                systemId: item,
                systemName: values.systemNameList[index],
                deviceId: values.deviceIdList[index],
                deviceName: values.deviceNameList[index],
                pointId: values.pointIdList[index],
                pointName: values.pointNameList[index],
                // 若未填写择为点位名称
                displayName: values.displayNameList[index] || values.pointNameList[index],
                color: values.colorList[index]
              }
            })
          }
          submitData.reportItems = submitData.reportItems.filter(item => item)
          if (values.id > 0) {
            try {
              const result = await updateChart(submitData)
              if (result) {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                this.findAllReportByPageId()
                this.$message.success('更新成功')
              }
            } finally {
              this.visible = false
              this.confirmLoading = false
            }
          } else {
            try {
              const result = await createChart(submitData)
              if (result) {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                this.findAllReportByPageId()
                this.$message.success('新增成功')
              }
            } finally {
              this.visible = false
              this.confirmLoading = false
            }
          }
        } else {
          this.confirmLoading = false
        }
      })
    }
  },
  mounted() {
  },
  updated() {
  },
  destroyed() {
  }
}
</script>
<style lang='less' scoped>

</style>